﻿using AForge;
using AForge.Imaging;
using AForge.Vision.Motion;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

namespace GameControler.AForge
{
    public class JilyAForge : IDisposable
    {

        MotionDetector detector = new MotionDetector(new TwoFramesDifferenceDetector(), new MotionAreaHighlighting());

        private int detectedObjectsCount = -1;

        public JilyAForge()
        {

            // detector.MotionDetectionAlgorithm = new SimpleBackgroundModelingDetector(false , false );
           
            var blob = new BlobCountingObjectsProcessing(80, 100, true);
           
            blob.HighlightColor = Color.FromArgb(0, 0, 0, 0);
            detector.MotionProcessingAlgorithm = blob;

        }

        public Bitmap JudgeFrame(Bitmap image)
        {
            lock (this)
            {
                if (detector != null && image != null)
                {
                    float motionLevel = detector.ProcessFrame(image);
                    var zones = detector.MotionZones;

                    if (detector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing)
                    {
                        BlobCountingObjectsProcessing countingDetector = (BlobCountingObjectsProcessing)detector.MotionProcessingAlgorithm;
                        var detectedObjectsCount = countingDetector.ObjectsCount;

                        BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat);

                        foreach (var item in countingDetector.ObjectRectangles)
                        {
                            if (item.Width < 300 && item.Height < 400)
                            {
                                Drawing.Rectangle(bitmapData, item, Color.Yellow);
                            }
                        }

                        image.UnlockBits(bitmapData);

                    }


                    return image;
                }
            }
            return null;
        }

        public void Dispose()
        {
            if (detector != null)
            {
                detector.Reset();
            }
        }
    }
}
